import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElSpace,
  ElButton,
  ElForm,
  ElRow,
  ElCol,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElRadioGroup,
  ElRadio,
  ElDatePicker,
  ElSwitch,
  ElTable,
  ElTableColumn,
  ElTimePicker,
  ElDivider,
  ElMessage,
  ElIcon,
  ElLink
} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { StrategyOptionStateType, FormValuesType } from './typings'
import type { fnStateEnum, taskForceEnum, circumferenceEnum } from '~/store/monitor/typings'
import type { FormInstance } from 'element-plus'
import AliIcon from '~/components/AliIocn'
import SaasTitle from '~/components/SaasTitle'
import useVuexGetters from '~/hooks/useVuexGetters'

export default defineComponent({
  name: 'StrategyOption',
  props: ['type', 'cancel', 'record'],
  setup(props: StrategyOptionStateType) {
    const store = useStore()
    const title = { add: '新增', update: '编辑', read: '查看' }
    const ruleFormRef = ref<FormInstance>()
    const switchState = useVuexGetters('switch', [
      'dictTypeOpt',
      'taskForceOpt',
      'circumferenceOpt',
      'taskTimeSlotOpt'
    ])
    const form = reactive<FormValuesType>({
      taskType: 1,
      taskTrem: 0,
      isLightCtr: 0,
      isOffset: 0,
      enabled: 1,
      detailList1: [],
      detailList2: [],
      detailList3: [],
      taskTremTime: []
    })
    onMounted(() => {
      //  任务类型
      store.dispatch('switch/DictTypeGet', { code: 'device_task_type' })
      //  任务组
      store.dispatch('switch/TaskForceGet', { ident: 'hardware' })

      taskPnChange(form?.taskType)
      form?.taskType === 1 && weekSun()
      props?.type !== 'add' && init()
    })
    //  详情数据
    const init = async () => {
      try {
        const { data } = await store.dispatch('switch/HardwareViewGet', { id: props.record.id })
        const taskGroupIds = data.taskGroupIds.split(',')
        const taskTremTime = [data.taskBegin, data.taskEnd]
        Object.assign(form, {
          id: data.id,
          taskName: data.taskName,
          taskDesc: data.taskDesc,
          taskPn: data.taskPn,
          taskType: data.taskType,
          taskTrem: data.taskTrem,
          isLightCtr: data.isLightCtr,
          lightCtrlTime: data.lightCtrlTime,
          onLightLux: data.onLightLux,
          offLightLux: data.offLightLux,
          isOffset: data.isOffset,
          onSumValue: data.onSumValue,
          offSunValue: data.offSunValue,
          enabled: data.enabled,
          taskGroupIds,
          taskTremTime,
          taskBegin: data.taskBegin,
          taskEnd: data.taskEnd,
          sort: data.sort,
          detailList1: data.detailList1,
          detailList2: data.detailList2,
          detailList3: data.detailList3
        })
      } catch (error) {}
    }
    //  方案号
    const taskPnChange = async (value: number | undefined) => {
      try {
        const { data } = await store.dispatch('switch/GetTaskPnGet', { taskType: value })
        form.taskPn = data
      } catch (error) {}
    }
    //  周任务
    const weekSun = async () => {
      try {
        const { data } = await store.dispatch('switch/GetWeekSunsierGet', {})
        form.detailList1 = data
      } catch (error) {}
    }
    //  多时段模式新增
    const onAdd = () => {
      form.detailList2?.push({
        lastOnTime: '',
        lastOffTime: ''
      })
    }
    //  多时段模式删除
    const onDel = (row: any) => {
      form.detailList2 = form.detailList2?.filter(
        (item: any, index: number) => index !== row.$index
      )
    }
    //  全天模式新增
    const onAdd1 = () => {
      form.detailList3?.push({
        isDayOper: 1
      })
    }
    //  全天模式删除
    const onDel1 = (row: any) => {
      form.detailList3 = form.detailList3?.filter(
        (item: any, index: number) => index !== row.$index
      )
    }
    // 提交表单
    const handleSubmitForm = () => {
      ruleFormRef.value?.validate(async (valid: boolean) => {
        if (!valid) return
        const taskBegin = form.taskTremTime?.[0]
        const taskEnd = form.taskTremTime?.[1]
        const taskGroupIds = form.taskGroupIds?.join(',')
        const params = {
          ...form,
          taskBegin,
          taskEnd,
          taskGroupIds
        }
        const res = await store.dispatch(
          props.type === 'add' ? 'switch/HardwareAddPost' : 'switch/HardwareUpdatePost',
          params
        )
        if (res?.code === 200) {
          ElMessage({ type: 'success', message: '操作成功' })
          props.cancel()
        }
      })
    }

    return () => (
      <ElCard
        v-slots={{
          header: () => (
            <ElSpace class="info-card-header-space">
              <SaasTitle type="primary">{(title[props.type] as string) || '查看'}</SaasTitle>
              <ElButton text type="primary" onClick={props.cancel}>
                返回上一级&nbsp;
                <AliIcon type="icon-fanhuishangyiji" />
              </ElButton>
            </ElSpace>
          )
        }}
      >
        <ElForm ref={ruleFormRef} model={form} labelWidth="116px" labelPosition="right">
          <ElRow>
            <ElCol span={12}>
              <ElFormItem
                label="任务名称"
                prop="taskName"
                rules={[{ required: true, message: '请输入任务名称', trigger: 'blur' }]}
              >
                {props.type !== 'read' ? (
                  <ElInput
                    v-model={form.taskName}
                    {...{ minlength: 2, maxlength: 50 }}
                    clearable
                    placeholder="请输入任务名称"
                  />
                ) : (
                  <div>{form.taskName}</div>
                )}
              </ElFormItem>
            </ElCol>
            <ElCol span={12}>
              <ElFormItem
                label="任务描述"
                prop="taskDesc"
                rules={[{ required: false, message: '请输入任务描述', trigger: 'blur' }]}
              >
                {props.type !== 'read' ? (
                  <ElInput
                    v-model={form.taskDesc}
                    {...{ minlength: 2, maxlength: 50 }}
                    clearable
                    placeholder="请输入任务描述"
                  />
                ) : (
                  <div>{form.taskDesc}</div>
                )}
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElRow>
            <ElCol span={12}>
              <ElFormItem
                label="方案号"
                prop="taskPn"
                rules={[{ required: true, message: '请输入方案号', trigger: 'blur' }]}
              >
                {props.type !== 'read' ? (
                  <ElInput
                    v-model={form.taskPn}
                    {...{ minlength: 2, maxlength: 50 }}
                    clearable
                    disabled={props?.type !== 'add'}
                    placeholder="请输入方案号"
                  />
                ) : (
                  <div>{form.taskPn}</div>
                )}
              </ElFormItem>
            </ElCol>
            <ElCol span={12}>
              <ElFormItem
                label="任务类型"
                prop="taskType"
                rules={[{ required: true, message: '请选择任务类型', trigger: 'change' }]}
              >
                {props.type !== 'read' ? (
                  <ElSelect
                    v-model={form.taskType}
                    filterable
                    clearable
                    disabled={props?.type !== 'add'}
                    placeholder="请选择任务类型"
                    onChange={taskPnChange}
                  >
                    {switchState.dictTypeOpt?.value?.map((item: fnStateEnum) => (
                      <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                    ))}
                  </ElSelect>
                ) : (
                  <div>{form.taskType}</div>
                )}
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElRow>
            <ElCol span={12}>
              <ElFormItem
                label="有效期"
                prop="taskTrem"
                rules={[{ required: false, message: '请选择有效期', trigger: 'change' }]}
              >
                <ElRadioGroup v-model={form.taskTrem}>
                  <ElRadio label={0}>长期</ElRadio>
                  <ElRadio label={1}>定期</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>
            {form.taskTrem === 1 && (
              <ElCol span={12}>
                <ElFormItem
                  label="时间"
                  prop="taskTremTime"
                  rules={[{ required: true, message: '请选择时间', trigger: 'change' }]}
                >
                  <ElDatePicker
                    v-model={form.taskTremTime}
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    value-format="yyyy-MM-dd"
                  />
                </ElFormItem>
              </ElCol>
            )}
          </ElRow>
          <ElRow>
            <ElCol span={12}>
              <ElFormItem
                label="启用光控"
                prop="isLightCtr"
                rules={[{ required: false, message: '请选择启用光控', trigger: 'change' }]}
              >
                <ElRadioGroup v-model={form.isLightCtr}>
                  <ElRadio label={0}>否</ElRadio>
                  <ElRadio label={1}>是</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>
            {form.isLightCtr === 1 && (
              <ElCol span={12}>
                <ElFormItem
                  label="光控时间范围"
                  prop="lightCtrlTime"
                  rules={[{ required: false, message: '请输入光控时间范围', trigger: 'blur' }]}
                >
                  {props.type !== 'read' ? (
                    <ElInput
                      v-model={form.lightCtrlTime}
                      {...{ minlength: 2, maxlength: 50 }}
                      clearable
                      placeholder="请输入光控时间范围"
                    />
                  ) : (
                    <div>{form.lightCtrlTime}</div>
                  )}
                </ElFormItem>
              </ElCol>
            )}
          </ElRow>
          {form.isLightCtr === 1 && (
            <ElRow>
              <ElCol span={12}>
                <ElFormItem
                  label="开灯光照值"
                  prop="onLightLux"
                  rules={[{ required: true, message: '请输入开灯光照值', trigger: 'blur' }]}
                >
                  {props.type !== 'read' ? (
                    <ElInput
                      v-model={form.onLightLux}
                      {...{ minlength: 2, maxlength: 50 }}
                      clearable
                      placeholder="请输入开灯光照值"
                    />
                  ) : (
                    <div>{form.onLightLux}</div>
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol span={12}>
                <ElFormItem
                  label="关灯光照值"
                  prop="offLightLux"
                  rules={[{ required: true, message: '请输入关灯光照值', trigger: 'blur' }]}
                >
                  {props.type !== 'read' ? (
                    <ElInput
                      v-model={form.offLightLux}
                      {...{ minlength: 2, maxlength: 50 }}
                      clearable
                      placeholder="请输入关灯光照值"
                    />
                  ) : (
                    <div>{form.offLightLux}</div>
                  )}
                </ElFormItem>
              </ElCol>
            </ElRow>
          )}
          <ElRow>
            <ElCol span={12}>
              <ElFormItem
                label="是否偏移"
                prop="isOffset"
                rules={[{ required: false, message: '请选择是否偏移', trigger: 'change' }]}
              >
                <ElRadioGroup v-model={form.isOffset}>
                  <ElRadio label={0}>否</ElRadio>
                  <ElRadio label={1}>是</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>
          </ElRow>
          {form?.isOffset === 1 && (
            <ElRow>
              <ElCol span={12}>
                <ElFormItem
                  label="开灯偏移值"
                  prop="onSumValue"
                  rules={[{ required: false, message: '请输入开灯偏移值', trigger: 'blur' }]}
                >
                  {props.type !== 'read' ? (
                    <ElInput
                      v-model={form.onSumValue}
                      {...{ minlength: 2, maxlength: 50 }}
                      clearable
                      placeholder="请输入开灯偏移值"
                    />
                  ) : (
                    <div>{form.onSumValue}</div>
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol span={12}>
                <ElFormItem
                  label="关灯偏移值"
                  prop="offSunValue"
                  rules={[{ required: false, message: '请输入关灯偏移值', trigger: 'blur' }]}
                >
                  {props.type !== 'read' ? (
                    <ElInput
                      v-model={form.offSunValue}
                      {...{ minlength: 2, maxlength: 50 }}
                      clearable
                      placeholder="请输入关灯偏移值"
                    />
                  ) : (
                    <div>{form.offSunValue}</div>
                  )}
                </ElFormItem>
              </ElCol>
            </ElRow>
          )}
          <ElRow>
            <ElCol span={12}>
              <ElFormItem
                label="是否启用"
                prop="enabled"
                rules={[{ required: false, message: '请输入是否启用', trigger: 'change' }]}
              >
                {props.type !== 'read' ? (
                  <ElSwitch
                    v-model={form.enabled}
                    active-text="是"
                    inactive-text="否"
                    active-value={1}
                    inactive-value={0}
                  />
                ) : (
                  <div>{form.enabled}</div>
                )}
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElRow>
            <ElCol span={12}>
              <ElFormItem
                label="任务组集合"
                prop="taskGroupIds"
                rules={[{ required: true, message: '请输入任务组集合', trigger: 'blur' }]}
              >
                {props.type !== 'read' ? (
                  <ElSelect
                    v-model={form.taskGroupIds}
                    filterable
                    clearable
                    multiple
                    placeholder="请选择任务类型"
                  >
                    {switchState.taskForceOpt?.value?.map((item: taskForceEnum) => (
                      <ElOption key={item?.id} label={item?.groupName} value={item?.id} />
                    ))}
                  </ElSelect>
                ) : (
                  <div>{form.taskGroupIds}</div>
                )}
              </ElFormItem>
            </ElCol>
            <ElCol span={12}>
              <ElFormItem
                label="排序"
                prop="sort"
                rules={[{ required: false, message: '请输入排序', trigger: 'blur' }]}
              >
                {props.type !== 'read' ? (
                  <ElInput
                    v-model={form.sort}
                    {...{ minlength: 1, maxlength: 50 }}
                    clearable
                    placeholder="请输入排序"
                  />
                ) : (
                  <div>{form.sort}</div>
                )}
              </ElFormItem>
            </ElCol>
          </ElRow>
          {form.taskType === 1 && (
            <ElRow>
              <ElCol span={24}>
                <ElFormItem label="周任务模式">
                  <ElTable data={form.detailList1} border>
                    <ElTableColumn
                      prop="taskTimeSlot"
                      label="周"
                      v-slots={{
                        default: ({ row }: any) => (
                          <ElSelect disabled v-model={row.taskTimeSlot}>
                            {switchState.circumferenceOpt?.value?.map((item: circumferenceEnum) => (
                              <ElOption
                                key={item?.dictKey}
                                label={item?.dictValue}
                                value={item?.dictKey}
                              />
                            ))}
                          </ElSelect>
                        )
                      }}
                    />
                    <ElTableColumn
                      prop="executionTime"
                      label="日期"
                      v-slots={{
                        default: ({ row }: any) => (
                          <ElDatePicker disabled type="date" v-model={row.executionTime} />
                        )
                      }}
                    />
                    <ElTableColumn
                      prop="lastOnTime"
                      label="开灯时间"
                      v-slots={{
                        default: ({ row }: any) => (
                          <ElTimePicker v-model={row.lastOnTime} value-format="HH:mm" />
                        )
                      }}
                    />
                    <ElTableColumn
                      prop="lastOffTime"
                      label="关灯时间"
                      v-slots={{
                        default: ({ row }: any) => (
                          <ElTimePicker v-model={row.lastOffTime} value-format="HH:mm" />
                        )
                      }}
                    />
                  </ElTable>
                </ElFormItem>
              </ElCol>
            </ElRow>
          )}
          {form.taskType === 2 && (
            <ElRow>
              <ElCol span={24}>
                <ElFormItem label="多时段模式">
                  <ElTable data={form.detailList2} border>
                    <ElTableColumn
                      v-slots={{
                        header: () => (
                          <ElButton type="primary" onClick={onAdd}>
                            <ElIcon>
                              <Plus />
                            </ElIcon>
                          </ElButton>
                        ),
                        default: (space: any) => (
                          <ElLink type="primary" onClick={() => onDel(space)}>
                            <AliIcon type="icon-shanchu" />
                            &nbsp; 删除
                          </ElLink>
                        )
                      }}
                    />
                    <ElTableColumn
                      prop="taskTimeSlot"
                      label="时段"
                      v-slots={{
                        default: ({ row }: any) => (
                          <ElSelect v-model={row.taskTimeSlot}>
                            {switchState.taskTimeSlotOpt?.value?.map((item: circumferenceEnum) => (
                              <ElOption
                                key={item?.dictKey}
                                label={item?.dictValue}
                                value={item?.dictKey}
                              />
                            ))}
                          </ElSelect>
                        )
                      }}
                    />
                    <ElTableColumn
                      prop="lastOnTime"
                      label="开灯时间"
                      v-slots={{
                        default: ({ row }: any) => (
                          <ElTimePicker v-model={row.lastOnTime} value-format="HH:mm" />
                        )
                      }}
                    />
                    <ElTableColumn
                      prop="lastOffTime"
                      label="关灯时间"
                      v-slots={{
                        default: ({ row }: any) => (
                          <ElTimePicker v-model={row.lastOffTime} value-format="HH:mm" />
                        )
                      }}
                    />
                  </ElTable>
                </ElFormItem>
              </ElCol>
            </ElRow>
          )}
          {form.taskType === 3 && (
            <ElRow>
              <ElCol span={24}>
                <ElFormItem label="全天模式设置">
                  <ElTable data={form.detailList3} border>
                    <ElTableColumn
                      v-slots={{
                        header: () => (
                          <ElButton type="primary" onClick={onAdd1}>
                            <ElIcon>
                              <Plus />
                            </ElIcon>
                          </ElButton>
                        ),
                        default: (space: any) => (
                          <ElLink type="primary" onClick={() => onDel1(space)}>
                            <AliIcon type="icon-shanchu" />
                            &nbsp; 删除
                          </ElLink>
                        )
                      }}
                    />
                    <ElTableColumn
                      prop="lastOffTime"
                      label="单选框组"
                      v-slots={{
                        default: ({ row }: any) => (
                          <ElRadioGroup v-model={row.isDayOper}>
                            <ElRadio label={1}>开灯</ElRadio>
                            <ElRadio label={0}>关灯</ElRadio>
                          </ElRadioGroup>
                        )
                      }}
                    />
                  </ElTable>
                </ElFormItem>
              </ElCol>
            </ElRow>
          )}
        </ElForm>
        {props.type !== 'read' && (
          <section class="fixed-option-btns">
            <ElDivider />
            <ElSpace class="form-options-btns">
              <ElButton plain onClick={props.cancel}>
                取消
              </ElButton>
              <ElButton type="primary" onClick={handleSubmitForm}>
                保存
              </ElButton>
            </ElSpace>
          </section>
        )}
      </ElCard>
    )
  }
})
